package jsyf.oa.web.report.attendance;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jsyf.com.util.*;
import jsyf.oa.facade.report.attendance.AttendanceFacade;
import jsyf.oa.web.until.ExportSignInExcel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by Administrator on 2018/4/7 0007.
 */
@Api(value = "新考勤报表", description = "新考勤报表")
@Controller
@RequestMapping("/attendance")
public class AttendanceController {

    @Resource
    private AttendanceFacade attendanceFacade;


    @RequestMapping(value = "/getSignPersonByToday.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "今日考勤数据",
            notes = "今日考勤数据",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM'}", dataType = "String", paramType = "body")
    public void getSignPersonByToday(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = attendanceFacade.getSignPersonByToday(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @ResponseBody
    @RequestMapping(value = "/getForPersonalByUserIdAndDateTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "获取个人月份考勤",
            notes = "获取个人月份考勤",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM'}", dataType = "String", paramType = "body")
    public void getForPersonalByUserIdAndDateTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForPersonalByUserIdAndDateTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/getSignInByUserId.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "获取某人某天是否签到、某个月的考勤汇总",
            notes = "获取某人某天是否签到、某个月的考勤汇总",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM'}", dataType = "String", paramType = "body")
    public void getSignInByUserId(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = attendanceFacade.getSignInByUserId(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/getSignInByRegionUserId.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "大区左侧汇总",
            notes = "大区左侧汇总",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM'}", dataType = "String", paramType = "body")
    public void getSignInByRegionUserId(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = attendanceFacade.getSignInByRegionUserId(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/getForDepartByUserIdAndDateTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "部门考勤报表",
            notes = "部门考勤报表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM-dd'}", dataType = "String", paramType = "body")
    public void getForDepartByUserIdAndDateTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForDepartByUserIdAndDateTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/getForCompanyByUserIdAndDateTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "公司考勤报表",
            notes = "公司考勤报表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM-dd'}", dataType = "String", paramType = "body")
    public void getForCompanyByUserIdAndDateTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForCompanyByUserIdAndDateTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/getForGroupByUserIdAndDateTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "集团考勤报表",
            notes = "集团考勤报表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM-dd'}", dataType = "String", paramType = "body")
    public void getForGroupByUserIdAndDateTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForGroupByUserIdAndDateTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/getForSignInByTypeAndDateTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "点击报表",
            notes = "点击报表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'companyId':''/departId:'','dateTime':'yyyy-MM-dd',type:'1,2,3'}", dataType = "String", paramType = "body")
    public void getForSignInByTypeAndDateTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForSignInByTypeAndDateTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/getForManagerInByTypeAndMonthTime.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "大区经理点击报表",
            notes = "大区经理点击报表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{'userId':'','dateTime':'yyyy-MM-dd',type:'1,2,3'}", dataType = "String", paramType = "body")
    public void getForManagerInByTypeAndMonthTime(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> jsonObjectList = this.attendanceFacade.getForManagerInByTypeAndMonthTime(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(jsonObjectList));
    }

    @RequestMapping(value = "/downExcelSignIn.json", method = RequestMethod.GET)
    public void downExcelServe(HttpServletResponse response, @RequestParam String dateTime, @RequestParam String companyId) throws Exception {
        //查出来的数据
        List<JSONObject> jsonObjectList = attendanceFacade.getShouldExcel(dateTime, companyId);
        getDownExcel(jsonObjectList, response, dateTime);
    }

    /**
     * @description: 考勤报表导出
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 18:16  2018/4/21 0021
     * @since: V1.0.0
     * @see jsyf.oa.web
     */

    public void getDownExcel(List<JSONObject> jsonObjectList, HttpServletResponse response, String dateTime
    ) throws Exception {
        String backGroud = attendanceFacade.getBackGround(dateTime);
        List<Integer> arrayDayList = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        String todayTime = DateUtils.parse(c.getTime(), "dd");
        //非当月，获取某月最后一天
        Integer lastDay = DateUtils.getLastDayOfMonth(Integer.valueOf(dateTime.split("-")[0]),
                Integer.valueOf(dateTime.split("-")[1]));
        for (Integer i = lastDay; i >= 1; i--) {
            arrayDayList.add(i < 10 ? (0 + i) : i);
        }
        List<String> strings = Lists.transform(arrayDayList, Functions.toStringFunction());
        //导出表名、列名
        String title = dateTime + "考勤明细";
        Object[] rowsName = new Object[]{"序号", "公司", "部门", "姓名", " "};
        // 通过toArray转换
        Object[] rowsCalendar = strings.toArray();
        Arrays.sort(rowsCalendar, new com());
        Object[] signIns = new Object[]{"标准出勤天数",
                "本月应休天数", "本月实休", "请假", "出勤", "加班", "原工资标准出勤天数", "备注"};
        Object[] newStr = new String[rowsName.length + rowsCalendar.length + signIns.length];
        for (int x = 0; x < rowsName.length; x++) {
            newStr[x] = rowsName[x];
        }
        for (int y = 0; y < rowsCalendar.length; y++) {
            newStr[rowsName.length + y] = rowsCalendar[y];
        }
        for (int z = 0; z < signIns.length; z++) {
            newStr[rowsName.length + rowsCalendar.length + z] = signIns[z];
        }

        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        Integer signInCount = DateUtils.getLastDayOfMonth(Integer.valueOf(dateTime.substring(0, 4)), Integer.valueOf(dateTime.substring(6, 7)));
        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jsonObject = jsonObjectList.get(i);
            String userId = jsonObject.getString("userId");
            String frontFlag = jsonObject.getString("frontFlag");
            objs = new Object[newStr.length];
            objs[0] = i + 1;
            objs[1] = jsonObject.get("companyName");
            objs[2] = jsonObject.get("departName");
            objs[3] = jsonObject.get("userName");
            objs[4] = jsonObject.get("main");

            if ("考勤".equals(jsonObject.getString("main"))) {
                List<JSONObject> shouldSignIn = attendanceFacade.getShouldByUserIdAndDateTime(jsonObject.getString("userId"), dateTime);
                String signs = "";
                for (int k = 0; k < shouldSignIn.size(); k++) {
                    signs += shouldSignIn.get(k).getString("signDate") + ",";
                }
                for (int j = 0; j < rowsCalendar.length; j++) {
                    String strRows = ExportSignInExcel.unitFormat(Integer.parseInt(rowsCalendar[j].toString()));
                    if (nowTime.equalsIgnoreCase(dateTime)) {
                        if (todayTime.compareTo(strRows) >= 0) {
                            if (signs.contains(strRows)) {
                                objs[j + 5] = "";
                            } else {
                                objs[j + 5] = "1";
                            }
                        } else {
                            objs[j + 5] = "";
                        }
                    } else {
                        if (signInCount.toString().compareTo(strRows) >= 0) {
                            if (signs.contains(strRows)) {
                                objs[j + 5] = "";
                            } else {
                                objs[j + 5] = "1";
                            }
                        } else {
                            objs[j + 5] = "";
                        }
                    }
                }
            } else if ("工作报告".equals(jsonObject.getString("main"))) {
                List<JSONObject> shouldSignIn = attendanceFacade.getWrtReportExcel(jsonObject.getString("userId"), dateTime);
                String signs = "";
                for (int k = 0; k < shouldSignIn.size(); k++) {
                    signs += shouldSignIn.get(k).getString("reportDate") + ",";
                }
                for (int j = 0; j < rowsCalendar.length; j++) {
                    String strRows = ExportSignInExcel.unitFormat(Integer.parseInt(rowsCalendar[j].toString()));
                    if (nowTime.equalsIgnoreCase(dateTime)) {
                        if (todayTime.compareTo(strRows) >= 0) {
                            if (signs.contains(strRows)) {
                                objs[j + 5] = "";
                            } else {
                                objs[j + 5] = "1";
                            }
                        } else {
                            objs[j + 5] = "";
                        }
                    } else {
                        if (signInCount.toString().compareTo(strRows) >= 0) {
                            if (signs.contains(strRows)) {
                                objs[j + 5] = "";
                            } else {
                                objs[j + 5] = "1";
                            }
                        } else {
                            objs[j + 5] = "";
                        }
                    }
                }
            }

            objs[newStr.length - 8] = jsonObject.get("shouldCount");
            objs[newStr.length - 7] = signInCount - jsonObject.getInteger("shouldCount");
            if (dateTime.equals(nowTime)) {
                objs[newStr.length - 6] = Integer.valueOf(todayTime) - attendanceFacade.getRealRest(dateTime, userId);
            } else {
                objs[newStr.length - 6] = signInCount - attendanceFacade.getRealRest(dateTime, userId);
            }
            objs[newStr.length - 5] = attendanceFacade.getLeaveRest(dateTime, userId, frontFlag);
            objs[newStr.length - 4] = attendanceFacade.getSignRest(dateTime, userId, frontFlag);
            objs[newStr.length - 3] = attendanceFacade.getOverTime(dateTime, userId, frontFlag);
            objs[newStr.length - 2] = "";
            objs[newStr.length - 1] = "";
            dataList.add(objs);
        }
        ExportSignInExcel ex = new ExportSignInExcel(title, newStr, dataList, response, backGroud, jsonObjectList, dateTime);
        ex.export();
    }

    class com<T> implements Comparator<T> {//对abcdefg进行比较大小，排序

        public int compare(T o1, T o2) {
            int i = Integer.parseInt(String.valueOf(o1));
            int j = Integer.parseInt(String.valueOf(o2));
            if (i > j) return 1;
            if (i < j) return -1;
            return 0;
        }
    }
}
